package com.likeyoudo.views.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.likeyoudo.common.BaseFragment;
import com.likeyoudo.views.R;
import com.likeyoudo.views.databinding.FragmentFilePreviewBinding;

/**
 * @author LikeYouDo
 * @date 2024/1/8 16:24
 */
public class FilePreviewFragment extends BaseFragment {

    private final String pdfPathPrefix = "file:///android_asset/pdf_js/web/viewer.html?file=";

    private String fileUrl;

    private FragmentFilePreviewBinding binding;

    public FilePreviewFragment(String fileUrl) {
        this.fileUrl = fileUrl;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_file_preview;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentFilePreviewBinding.inflate(inflater, container, false);
        // 设置文件
        initView();
        return binding.getRoot();
    }

    private void initView() {
        // 设置WebView支持JavaScript
        WebSettings settings = binding.filePreview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);


        // 支持缩放
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);


        // 创建自定义的WebViewClient和WebChromeClient
        binding.filePreview.setWebViewClient(new WebViewClient());
        binding.filePreview.setWebChromeClient(new WebChromeClient());


        // 加载pdf.js的pdf.html，并传递PDF文件路径作为参数
        binding.filePreview.loadUrl(pdfPathPrefix + fileUrl);
    }

    public void reloadPdf() {
        // 加载pdf.js的pdf.html，并传递PDF文件路径作为参数
        // binding.filePreview.loadUrl(pdfPathPrefix + fileUrl);

        //调用函数,重置缩放比例
        // 调用JavaScript代码以重置PDF的缩放比例至默认值
        String jsCode = "var pdfViewerApp = (typeof PDFViewerApplication !== 'undefined') ? PDFViewerApplication : null;" +
                "if (pdfViewerApp) {" +
                "  pdfViewerApp.pdfViewer.currentScaleValue = 'page-width';" +
                "  pdfViewerApp.pdfViewer.update();" +
                "}";

        binding.filePreview.evaluateJavascript(jsCode, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                // 这里是处理执行结果的地方（如果有的话），但此处重置缩放比例可能不会返回任何值
            }
        });
    }

}
